package com.bite.common.utils;

import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

import java.io.UnsupportedEncodingException;
import java.util.Optional;

public class MailClient {
    private final JavaMailSender javaMailSender;
    private final MailProperties mailProperties; // 邮件配置内容

    public MailClient(JavaMailSender javaMailSender, MailProperties mailProperties) {
        this.javaMailSender = javaMailSender;
        this.mailProperties = mailProperties;
    }


    public void send(String to, String subject, String text) throws MessagingException, UnsupportedEncodingException {
        MimeMessage message = javaMailSender.createMimeMessage();

        MimeMessageHelper helper = new MimeMessageHelper(message, false);

        String personal = Optional.ofNullable(mailProperties.getProperties().get("personal")).orElse(mailProperties.getUsername()); // 如果 personal 为空 那么就为 mailProperties.getUsername()

        helper.setFrom(mailProperties.getUsername(), personal);
        helper.setText(text, true); // 开启html转换
        helper.setSubject(subject);
        helper.setTo(to);

        javaMailSender.send(message);
    }
}
